package tree_util;

import com.common.RequestDataTool;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.sun.xml.internal.ws.message.ProblemActionHeader;
import db_tool.DBConnection;
import db_tool.LogTool;
import db_tool.TimeFormat;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.io.File;
import java.io.PrintWriter;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

/**
 * 添加、更新、删除	 监测点
 * */
public class Op_MonitoringSite extends ActionSupport {

	private String flag;		//区分操作
	
	private final static String START = "MON";				//主键、照片 开头
	
	private static String PATH = "";					//照片在服务器上的路径("|"隔开)
	
	private String InverstigationID;				
	private String Institution;
	private String Investigator;
	private String InvestigationDate;
	private String Site;
	private String River;
	private String StartTime;
	private String EndTime;
	private String StartLongitude;
	private String StartLatitude;
	private String EndLongitude;
	private String EndLatitude;
	private String Weather;
	private String Temperature;
	
	private List<File> Photo;					//文件引用
	private List<String> PhotoFileName;			//文件名字
	private List<String> PhotoContentType;		//文件类型
	private String isNull;
	
	private String deletePhoto;
	private String NodeName;
	
	private PrintWriter writer = null;
	
	private DBConnection db_connection = null;
	
	private Account account = null;
	private RequestDataTool requestDataTool;
	
	@Override
	public String execute() throws Exception {
		// TODO Auto-generated method stub
		ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");

        ApplicationContext context = new ClassPathXmlApplicationContext("Spring-Module.xml");
        requestDataTool = (RequestDataTool) context.getBean("requestDataTool");
		writer = ServletActionContext.getResponse().getWriter();
		db_connection = DBConnection.getInstance();
		//获取session中保存的用户信息
		account = (Account) ActionContext.getContext().getSession().get("account");
		System.out.println(Temperature);
		if(StartLongitude.equals("0E-9")) {StartLongitude="0";}
		if(StartLatitude.equals("0E-9")) {StartLatitude="0";}
		if(EndLongitude.equals("0E-9")) {EndLongitude="0";}
		if(EndLatitude.equals("0E-9")) {EndLatitude="0";}
		if(Temperature.equals("0E-9")) {Temperature="0";}
		int siteLength = Site.substring(Site.lastIndexOf('-')).length();
		if(Institution != null && Institution.equals("")||Investigator != null && Investigator.equals("")
				||siteLength<=1||River != null && River.equals("")) {
			writer.write("null");
			writer.flush();
			writer.close();
		}
		else {
			if(flag.equals("insert")){
				//插入操作
				insert();
                LogTool.insertIntoDataLog(LogTool.INSERT_CODE, "MonitoringSite", 1);
			}else if(flag.equals("update")){
				//更新操作
				update();
                LogTool.insertIntoDataLog(LogTool.UPDATE_CODE, "MonitoringSite", 1);

            }if(flag.equals("delete")){
                delete();
                LogTool.insertIntoDataLog(LogTool.DELETE_CODE, "MonitoringSite", 1);

            }
		}
		return null;
	}
	
	private void delete(){
	    PATH = UpLoadPicture.Delete(NodeName,deletePhoto);
	    String update = "update MonitoringSite set Photo='"
				+ PATH + "' where InverstigationID='" + NodeName + "'";
		System.out.println(update);
		Statement statement = null;
		try {
			statement = db_connection.getStatement();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			statement.executeUpdate(update);
			writer.write(PATH);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			writer.write("error");
			e.printStackTrace();
		} finally{
			try {
				db_connection.close(statement);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}
	
	private void update(){
//        System.out.println("更新操作");
//        //获取照片路径
//		if(isNull.length()!=0)
//		    PATH = UpLoadPicture.upload(Photo, PhotoFileName, InverstigationID);
//		if(PATH.equals("photo_error")){			//照片出错
//			writer.write("photo_error");
//		} else{
//            if (StartTime.equals("null") || EndTime.equals("null")) {
//                writer.write("null");
//            }
//			int num = requestDataTool.updateMoniterSite(Institution, Investigator, InvestigationDate, Site, River, PATH
//                    , StartTime, EndTime, StartLongitude, StartLatitude, EndLongitude, EndLatitude, Weather, Temperature
//                    , InverstigationID);
//            System.out.println("更新的数量"+num);
//            if (num != 0) {
//			    writer.write(PATH);
//            } else {
//			    writer.write("error");
//            }
//		}
        if(isNull.length()!=0)
            PATH = UpLoadPicture.upload(Photo, PhotoFileName, InverstigationID);
        if(PATH.equals("photo_error")){			//照片出错
            writer.write("photo_error");
        }else{
            String sql = "";
            sql += "update MonitoringSite set Institution='" + Institution + "',Investigator='" + Investigator + "',InvestigationDate='" + InvestigationDate + "',Site='";
            sql += Site + "',River='" + River + "',Photo='" + PATH + "',StartTime='" + StartTime + "',EndTime='" + EndTime + "',StartLongitude='" + StartLongitude + "',StartLatitude='";
            sql += StartLatitude + "',EndLongitude='" + EndLongitude + "',EndLatitude='" + EndLatitude + "',Weather='" + Weather + "',Temperature='" + Temperature + "'";
            sql += " where InverstigationID='" + InverstigationID + "'";
            System.out.println(StartTime);
            System.out.println(EndTime);
            if (StartTime.equals("null") || EndTime.equals("null")) {
                writer.write("null");
            }
            Statement statement = null;
            try {
                statement = db_connection.getStatement();
            } catch (SQLException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

            try {
                assert statement != null;
                statement.executeUpdate(sql);
                writer.write(PATH);
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                writer.write("error");
                System.out.println("sql语句在上面");
                System.out.println("--监测点更新失败--");
                System.out.println(sql);
                e.printStackTrace();
            } finally{
                try {
                    db_connection.close(statement);
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    System.out.println("监测点更新操作关闭失败");
                    e.printStackTrace();
                }
            }
        }
	}
	
	private void insert(){
		
		String childID = START + TimeFormat.getNowTime();
		
		//获取照片路径
		if(isNull.length()!=0)
		PATH = UpLoadPicture.upload(Photo, PhotoFileName, childID);
		if(PATH.equals("photo_error")){			//照片出错
			writer.write("photo_error");
		}else{
			String insert = "insert into MonitoringSite values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
			
			PreparedStatement preparedStatement = null;
			try {
				preparedStatement = db_connection.getPreparedStatement(insert);
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			try {
				preparedStatement = db_connection.getPreparedStatement(insert);
				preparedStatement.setString(1, childID);
				preparedStatement.setString(2, Institution);
				preparedStatement.setString(3, Investigator);
				preparedStatement.setString(4, InvestigationDate);
				preparedStatement.setString(5, Site);
				preparedStatement.setString(6, River);
				preparedStatement.setString(7, PATH);
				preparedStatement.setString(8, StartTime);
				preparedStatement.setString(9, EndTime);
				preparedStatement.setString(10, StartLongitude);
				preparedStatement.setString(11, StartLatitude);
				preparedStatement.setString(12, EndLongitude);
				preparedStatement.setString(13, EndLatitude);
				preparedStatement.setString(14, Weather);
				preparedStatement.setString(15, Temperature);
				preparedStatement.setString(16, account.getID());
				
				preparedStatement.executeUpdate();
				
				writer.write(childID);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				writer.write("error");
				System.out.println("--监测点插入错误--");
				e.printStackTrace();
			}finally{
				try {
					db_connection.close(preparedStatement);
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					System.out.println("监测点插入操作关闭失败");
					e.printStackTrace();
				}
			}
		}
	}

	public String getInverstigationID() {
		return InverstigationID;
	}

	public void setInverstigationID(String inverstigationID) {
		InverstigationID = inverstigationID;
	}

	public String getInstitution() {
		return Institution;
	}

	public void setInstitution(String institution) {
		Institution = institution;
	}

	public String getInvestigator() {
		return Investigator;
	}

	public void setInvestigator(String investigator) {
		Investigator = investigator;
	}

	public String getInvestigationDate() {
		return InvestigationDate;
	}

	public void setInvestigationDate(String investigationDate) {
		InvestigationDate = investigationDate;
	}

	public String getSite() {
		return Site;
	}

	public void setSite(String site) {
		Site = site;
	}

	public String getRiver() {
		return River;
	}

	public void setRiver(String river) {
		River = river;
	}

	public String getStartTime() {
		return StartTime;
	}

	public void setStartTime(String startTime) {
		StartTime = startTime;
	}

	public String getEndTime() {
		return EndTime;
	}

	public void setEndTime(String endTime) {
		EndTime = endTime;
	}

	public String getStartLongitude() {
		return StartLongitude;
	}

	public void setStartLongitude(String startLongitude) {
		StartLongitude = startLongitude;
	}

	public String getStartLatitude() {
		return StartLatitude;
	}

	public void setStartLatitude(String startLatitude) {
		StartLatitude = startLatitude;
	}

	public String getEndLongitude() {
		return EndLongitude;
	}

	public void setEndLongitude(String endLongitude) {
		EndLongitude = endLongitude;
	}

	public String getEndLatitude() {
		return EndLatitude;
	}

	public void setEndLatitude(String endLatitude) {
		EndLatitude = endLatitude;
	}

	public String getWeather() {
		return Weather;
	}

	public void setWeather(String weather) {
		Weather = weather;
	}

	public String getTemperature() {
		return Temperature;
	}

	public void setTemperature(String temperature) {
		Temperature = temperature;
	}

	public String getFlag() {
		return flag;
	}

	public void setFlag(String flag) {
		this.flag = flag;
	}

	public List<File> getPhoto() {
		return Photo;
	}

	public void setPhoto(List<File> photo) {
		Photo = photo;
	}

	public List<String> getPhotoFileName() {
		return PhotoFileName;
	}

	public void setPhotoFileName(List<String> photoFileName) {
		PhotoFileName = photoFileName;
	}

	public List<String> getPhotoContentType() {
		return PhotoContentType;
	}

	public void setPhotoContentType(List<String> photoContentType) {
		PhotoContentType = photoContentType;
	}
	
	public String getDeletePhoto(){
		return deletePhoto;
	}
	
	public void setDeletePhoto(String deletePhoto){
		this.deletePhoto=deletePhoto;
	}
	
	public String getNodeName(){
		return NodeName;
	}
	
	public void setNodeName(String NodeName){
		this.NodeName=NodeName;
	}
	
	public String getIsNull(){
		return isNull;
	}
	
	public void setIsNull(String isNull){
		this.isNull=isNull;
	}

}
